package fun.scxsh.webproject.dao;

import fun.scxsh.webproject.entity.Student;
import fun.scxsh.webproject.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {
    // 分页显示条数
    public static final int PAGE_SIZE = 5;

    /**
     * 获取学生页面
     * @param page
     * @return
     */
    public List<Student> getStudentByPage(int page) {
        List<Student> students = new ArrayList<Student>();
        String sql =  "select * from students limit ? , ?";
        try(
                Connection conn = DBUtil.getConn();
                PreparedStatement ps = conn.prepareStatement(sql);
                ) {
            int startIndex = (page - 1) * PAGE_SIZE;
            ps.setInt(1, startIndex);
            ps.setInt(2, PAGE_SIZE);
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                Student student = new Student(
                        rs.getInt("age"),
                        rs.getInt("id"),
                        rs.getString("name")
                );
                students.add(student);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return students;
    }

    /**
     * 获取
     * @return
     */
    public int getTotalCount() {
        int count = 0;
        String sql = "SELECT COUNT(*) FROM students";
        try (Connection connection = DBUtil.getConn();
             PreparedStatement preparedStatement = connection.prepareStatement(sql);
             ResultSet resultSet = preparedStatement.executeQuery()) {
            if (resultSet.next()) {
                count = resultSet.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}
